//
//  MGShareManager.m
//  MortgageHelper
//
//  Created by zhangxiang on 16/8/23.
//  Copyright © 2016年 zhangxiang. All rights reserved.
//

#import "MGShareManager.h"

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

#define WeixinId @"wxdfdffdef5340c8f5"

#define QQId @"1105101920"

//微信SDK头文件
#import "WXApi.h"

#import "ZXShareViewController.h"

#import "MGConstFile.h"


//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"
static MGShareManager *_sharedManager=nil;


@implementation MGShareManager
{
    TencentOAuth *tencentOAuth;
}

+(MGShareManager *)sharemanager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [MGShareManager new];
        [_sharedManager registerShareforApp];
    });
    return _sharedManager;
    
}
// 注册各平台的分享设置
-(void)registerShareforApp{
    
    
    [WXApi registerApp:WeixinId withDescription:@"按揭帮"];
    
    tencentOAuth=[[TencentOAuth alloc] initWithAppId:QQId andDelegate:nil]; //注册
    
}

-(void)shareWithtitle:(NSString *)title description:(NSString *)description url:(NSString *)url thumbImage:(UIImage *)image onView:(UIViewController *)viewController {
    

    ZXShareViewController * Vc=[ZXShareViewController viewWithSelfNib];
   
    [KEY_WINDOW addSubview:Vc];
    [Vc customInit];
    [Vc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(KEY_WINDOW).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    if (!image) {
        image=[UIImage imageNamed:@"icon120x120px.png"];
    }
    WEAK_SELF
    Vc.retrunTypeBlock=^(NSInteger index){
        if (index==0) {
            STRONG_SELF
            [strongSelf shareToWeChat:title description:description url:url thumbImage:image];

        }else{
            STRONG_SELF
            [strongSelf shareToQQ:title description:description url:url thumbImage:image];
 
        }
    };

}
-(void)lzyShareWithtitle:(NSString *)title description:(NSString *)description url:(NSString *)url thumbImage:(UIImage *)image onView:(UIViewController *)viewController
{
    ZXShareViewController * Vc=[ZXShareViewController viewWithSelfNib];
    Vc.wxpyqimage.image = [UIImage imageNamed:@"wx_circle"];
    Vc.pyqtitle.text = @"朋友圈";
    [KEY_WINDOW addSubview:Vc];
    [Vc customInit];
    [Vc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(KEY_WINDOW).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    if (!image) {
        image=[UIImage imageNamed:@"icon120x120px.png"];
    }
    WEAK_SELF
    Vc.retrunTypeBlock=^(NSInteger index){
        if (index==0) {
            STRONG_SELF
            [strongSelf shareToWeChat:title description:description url:url thumbImage:image andType:1];
            
        }else{
            STRONG_SELF
            [strongSelf shareToWeChat:title description:description url:url thumbImage:image andType:2];
            
        }
    };
}
// 微信分享链接
-(void)shareToWeChat:(NSString *)title description:(NSString *)description url:(NSString *)url thumbImage:(UIImage *)image andType:(int)type{
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = description;
    [message setThumbImage:image];  // [UIImage imageNamed:@"icon120x120px.png"]
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = url;
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* resp = [[SendMessageToWXReq alloc] init];
    resp.message = message;
    resp.bText = NO;
    if(type == 1)
    {
        resp.scene = WXSceneSession;
    }else
    {
        resp.scene = WXSceneTimeline;
    }
    
    [WXApi sendReq:resp];
    
}

#pragma mark

- (void)shareToQQ:(NSString *)title description:(NSString *)description url:(NSString *)url thumbImage:(NSString *)image {
    if (![TencentOAuth iphoneQQInstalled]) {
        
    }else {
        tencentOAuth = [[TencentOAuth alloc] initWithAppId:QQId
                                                    andDelegate:nil];
    
        QQApiNewsObject *newsObj = [QQApiNewsObject
                                    objectWithURL:[NSURL URLWithString:url]
                                    title:title
                                    description:description
                                    previewImageURL:[NSURL URLWithString:@"https://img.jingjibang.cn/3A0C633B612C4E88A9AB2834A6150321.jpg"]];
                                    
        SendMessageToQQReq *req = [SendMessageToQQReq reqWithContent:newsObj];
        
       [QQApiInterface sendReq:req];
        
    }
}



#pragma mark 微信


// 微信分享链接
-(void)shareToWeChat:(NSString *)title description:(NSString *)description url:(NSString *)url thumbImage:(UIImage *)image{
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description = description;
    [message setThumbImage:image];  // [UIImage imageNamed:@"icon120x120px.png"]
    
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = url;
    
    message.mediaObject = ext;
    
    GetMessageFromWXResp* resp = [[GetMessageFromWXResp alloc] init];
    resp.message = message;
    resp.bText = NO;
    
    [WXApi sendResp:resp];

}


// 微信分享图片
- (void) lzySendImageContent:(UIImage *)ScreenImage thumbImage:(UIImage *)image
{
    ZXShareViewController * Vc=[ZXShareViewController viewWithSelfNib];
    Vc.wxpyqimage.image = [UIImage imageNamed:@"wx_circle"];
    Vc.pyqtitle.text = @"朋友圈";
    [KEY_WINDOW addSubview:Vc];
    [Vc customInit];
    [Vc mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(KEY_WINDOW).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    if (!image) {
        image=[UIImage imageNamed:@"icon120x120px.png"];
    }
    WEAK_SELF
    Vc.retrunTypeBlock=^(NSInteger index){
        if (index==0) {
            STRONG_SELF
            [strongSelf shareImageContent:ScreenImage thumbImage:image andType:1];
            
        }else{
            STRONG_SELF
            [strongSelf shareImageContent:ScreenImage thumbImage:image andType:2];
            
        }
    };
}

- (void) shareImageContent:(UIImage *)ScreenImage thumbImage:(UIImage *)image andType:(int)type
{
    WXMediaMessage *message = [WXMediaMessage message];
    [message setThumbImage:image];
    
    WXImageObject *ext = [WXImageObject object];
    //    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"res5thumb" ofType:@"png"];
    //    NSLog(@"filepath :%@",filePath);
    //    ext.imageData = [NSData dataWithContentsOfFile:filePath];
    //
    //    //UIImage* image = [UIImage imageWithContentsOfFile:filePath];
    //    UIImage* image = [UIImage imageWithData:ext.imageData];
    ext.imageData = UIImagePNGRepresentation(ScreenImage);
    
    //    UIImage* image = [UIImage imageNamed:@"res5thumb.png"];
    //    ext.imageData = UIImagePNGRepresentation(image);
    
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    if(type == 1)
    {
      req.scene = WXSceneSession;
    }else
    {
      req.scene = WXSceneTimeline;
    }
    
    
    [WXApi sendReq:req];
}

//-(void) onReq:(BaseReq*)req
//{
//    if([req isKindOfClass:[GetMessageFromWXReq class]])
//    {
//        // 微信请求App提供内容， 需要app提供内容后使用sendRsp返回
//        NSString *strTitle = [NSString stringWithFormat:@"微信请求App提供内容"];
//        NSString *strMsg = @"微信请求App提供内容，App要调用sendResp:GetMessageFromWXResp返回给微信";
//        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        alert.tag = 1000;
//        [alert show];
//       
//    }
//    else if([req isKindOfClass:[ShowMessageFromWXReq class]])
//    {
//        ShowMessageFromWXReq* temp = (ShowMessageFromWXReq*)req;
//        WXMediaMessage *msg = temp.message;
//        
//        //显示微信传过来的内容
//        WXAppExtendObject *obj = msg.mediaObject;
//        
//        NSString *strTitle = [NSString stringWithFormat:@"微信请求App显示内容"];
//        NSString *strMsg = [NSString stringWithFormat:@"标题：%@ \n内容：%@ \n附带信息：%@ \n缩略图:%lu bytes\n\n", msg.title, msg.description, obj.extInfo, (unsigned long)msg.thumbData.length];
//        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alert show];
//       
//    }
//    else if([req isKindOfClass:[LaunchFromWXReq class]])
//    {
//        //从微信启动App
//        NSString *strTitle = [NSString stringWithFormat:@"从微信启动"];
//        NSString *strMsg = @"这是从微信启动的消息";
//        
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//        [alert show];
//    
//    }
//}


-(void)chatWithWeixin{
    
//    JumpToBizProfileReq *req = [[JumpToBizProfileReq alloc]init];
//    req.profileType =WXBizProfileType_Normal;
//    //    enum WXBizProfileType{
//    //        WXBizProfileType_Normal = 0, /*普通公众号添加这一段代码 */
//    //        WXBizProfileType_Device = 1, /*硬件公众号添加这一段代码*/
//    //    };
//    req.username =@"gh_ee43601f45e2"; /*公众号原始ID*/
//    //    req.extMsg = @"extMsg"; /*若为服务号或订阅号则本字段为空，硬件号则填写相关的硬件二维码串*/
//    [WXApi sendReq:req];
}
//- (void)onReq:(QQBaseReq *)req {
//    
//}

//// 处理来自QQ的响应，调用sendReq
//- (void)onResp:(QQBaseReq *)resp {
//    switch (resp.type)
//    {
//        case ESENDMESSAGETOQQRESPTYPE:
//        {
//            SendMessageToQQResp* sendResp = (SendMessageToQQResp*)resp;
//            if ([sendResp.result isEqualToString:@"0"]) {
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"成功" message:@"QQ分享成功" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                [alert show];
//            }
//            else {
//                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"失败" message:@"QQ分享失败" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                [alert show];
//            }
//            break;
//        }
//        default:
//        {
//            break;
//        }
//    }
//}
//

@end
